<template>
  <div class="dialogForm">
      <el-dialog
        v-model="dialogVisible"
        title="租单信息"
        draggable
        width="35%">
        <el-form :model="form" class="demo-ruleForm" size="large">

          <el-form-item label="姓名" label-width="120px">
            <el-input v-model="form.username" type="text" autocomplete="off" placeholder="请留下您姓名" />
          </el-form-item>

          <el-form-item label="联系方式" label-width="120px">
            <el-input v-model="form.phone" type="text" autocomplete="off" placeholder="请留下您的联系方式" />
          </el-form-item>

          <el-form-item label="还车日期" label-width="120px">
              <el-date-picker v-model="form.backTime" format="YYYY-MM-DD" @change="selectDate"
              value-format="YYYY-MM-DD"  placeholder="请填写换车日期" style="width: 100%;"/>
          </el-form-item>

          <el-form-item label="预借天数:" label-width="120px">
              <div style="text-indent: 10px;color: gray;font-size: 15px;font-weight: bold;"><span style="color: crimson;">{{ rentDay }}</span> / 天（24H）</div>
          </el-form-item>

          <el-form-item label-width="120px">
              <span style="font-size: 18px;color: red;">*</span> 金额 <h2 style="margin-left: 20px;color: crimson;"> {{ price }} ￥</h2>
          </el-form-item>

        </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submit()" style="width: 80%;margin-right: 8%;height: 40px;" :loading="isLoading">
            确认并支付
          </el-button>
        </span>
      </template>
    </el-dialog>
    <messageComp ref="ref_messageComp"></messageComp>
    <payComp v-if="isPlaying"></payComp>
  </div>
</template>

<script setup>
import axios from "axios";
import messageComp from "../components/messageComp.vue";
import payComp from "./payment.vue";
const ref_messageComp = ref(null) //弹窗message组件refs
import { ref,provide } from "vue"
import { useStore } from 'vuex'
const store = useStore()
import { dayjs } from 'element-plus';
// 数据
let carData = ref({})
let rentDay = ref(1)
let isLoading = ref(false)
const dialogVisible = ref(false)
let form = ref({})
let price = ref(0)
let isPlaying = ref(false)
let userInfo = ref(store.state.userInfo)
//  函数
const changeDialogVisible = (parentData)=>{
  dialogVisible.value = true
  carData.value = parentData
  price.value = carData.value.price
}
const selectDate = (e)=>{
  price.value = carData.value.price //每次触发都回到最初的金额
  const today = dayjs();
  const selected = dayjs(e);
  rentDay.value = selected.diff(today, 'day') + 1; //选择后的日期减去今天 ----借了几天车
  if (rentDay.value<=0) {
    ref_messageComp.value.messageInfo('选择的日期不可晚于今天')
    form.value.date = undefined //清空掉值
    return; // selected date is before today
  }
  price.value =  (price.value * rentDay.value)
  console.log('选择日期',e,rentDay.value,price.value);
}

const submit = ()=>{
  if (form.value.username == undefined || form.value.phone == undefined || form.value.backTime == undefined) {
    // console.log(dayjs(form.value.date).diff(dayjs(), 'day'));
    ref_messageComp.value.messageWarning('请填写完整信息!')
    console.log(form.value);
    return;
  }
  ref_messageComp.value.loading({text:'正在校验支付中..',dom:'el-dialog'},1500,()=>{
    if (userInfo.value != undefined) {
      isPlaying.value = true //开启支付
    } else {
      ref_messageComp.value.messageFail('对不起，您尚未登录！')
    }
  })
}
const finishPay = ()=>{ //完成支付
  isPlaying.value = false
  createOrder()
}
provide('confirm',finishPay) //把确认按钮传给子组件
// 模拟支付函数
const createOrder = ()=>{
  let data = {}
  // 订单所需信息
  data.username = form.value.username
  data.phone = form.value.phone
  data.userId = userInfo.value.id
  data.title = carData.value.name
  data.carId = carData.value.id
  data.rentTime = dayjs().format('YYYY-MM-DD')
  data.backTime = form.value.backTime
  data.rentDay = rentDay.value
  data.rentPrice = price.value
  axios({
    method:'post',
    url:store.state.url + '/orders/insert',
    data
  }).then(res=>{
    if (res.data.code == 200) {
      ref_messageComp.value.messageSuccess('订单创建成功')
      return;   
    }
    console.log(res);
    ref_messageComp.value.messageFail('订单创建失败')
  }).catch(err=>{
    console.log(err);
    ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
  })
}
// 暴露方法
defineExpose({
  changeDialogVisible
})
 
</script>

<style scoped>
div /deep/ form{
  margin-top: -20px;
  margin-bottom: -20px;
  padding-top: 10px;
  padding-right: 10px;
  width: 100% !important;
  height: 100% !important; 
  background-color: white;
}
div /deep/ .el-dialog__title{
  color: gray;
  letter-spacing: 4px;
}

</style>